<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib prefix="tag" tagdir="/WEB-INF/tags"%>
<html>
<head>
<tag:header />
</head>
<body id="main_layout">
	<div id="pageGrid"></div>
    <div id="dd"></div>
	<script type="text/template" id="pageGridTmpl">
    <form>
		    <!--标题-->
			<div class="col">
				<input id="title" data-qfield="title" class="query" data-qoperator="EQUAL" data-qtype="STRING"/>
			</div>

			<!--发送状态-->
			<div class="col">
				<select id="sendStatus" data-qfield="sendStatus" class="easyui-combobox query" data-options="editable:false" data-qoperator="EQUAL" data-qtype="STRING">
					<option value="">所有</option>
					<option value="0">未发送</option>
					<option value="1">已发送</option>
				</select>
			</div>

			<!--开始时间-->
        	<div class="col">
				<input id="startTime" data-qfield="startTime" class="easyui-datebox query" data-qoperator="GREATER" data-qtype="DATE"/>
			</div>

	        <!--结束时间-->
        	<div class="col">
				<input id="endTime" data-qfield="endTime" class="easyui-datebox query" data-qoperator="LESS" data-qtype="DATE"/>
			</div>

			<!--增加人-->
			<div class="col">
				<input id="addBy" data-qfield="addBy" class="query" data-qoperator="EQUAL" data-qtype="STRING"/>
			</div>

			<!--发起人-->
			<div class="col">
				<input id="sender" data-qfield="sender" class="query" data-qoperator="EQUAL" data-qtype="STRING"/>
			</div>

    </form>
</script>
<script type="text/javascript">
    Date.prototype.format = function(fmt) {
        var o = {
            "M+" : this.getMonth()+1,                 //月份
            "d+" : this.getDate(),                    //日
            "h+" : this.getHours(),                   //小时
            "m+" : this.getMinutes(),                 //分
            "s+" : this.getSeconds(),                 //秒
            "q+" : Math.floor((this.getMonth()+3)/3), //季度
            "S"  : this.getMilliseconds()             //毫秒
        };
        if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        }
        for(var k in o) {
            if(new RegExp("("+ k +")").test(fmt)){
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
            }
        }
        return fmt;
    }

	var pagegrid;
	(function() {
		//参数配置
		var options = {
			containerId : 'pageGrid',
			pageGridTmplId : 'pageGridTmpl',
			contextUrl : '${pageContext.request.contextPath}',
			module : '${module}',
			submodule : '${submodule}',
			moduleName : '问卷',
			useCommonApi: false,
			instantSearch : true
		};

		options.datagridOptions = {
            onDblClickRow: function (index, row) {
                $(this).datagrid('unselectAll');
                $(this).datagrid('selectRow', index);
                pagegrid.openView();
            }
		};
		
		/** 设置自定义按钮事件处理方法 **/
        options.btnHandlers = {
            "onEdit":function(pg){
                var rows = pagegrid.getMultiSelected();

                if (!rows || rows.length === 0) {
                    $.messager.alert('警告', "请选择数据！", "warning");
                    return;
                }

                if(rows.length > 1){
                    $.messager.alert('警告', "每次只能修改一条！", "warning");
                    return;
                }

                var row = rows[0];
                // 0 未发送 1已发送
                if('1'==row.SENDSTATUS){
                    $.messager.alert('提示', '所选行中存在已发送数据，无法编辑', 'warning');
                    return false;
                }

                pagegrid.openEdit();
            },
            "onSend":function(pg){
                var rows = pagegrid.getMultiSelected();

                if (!rows || rows.length === 0) {
                    $.messager.alert('警告', "请选择数据！", "warning");
                    return;
                }

                var _flag = true;

                var currentTime = new Date().format("yyyy-MM-dd hh:mm:ss");
                console.log(currentTime);
                $.each(rows,function(_index,_object){

                    if(!(_object.STARTTIME <= currentTime && _object.ENDTIME >= currentTime)){
                        $.messager.alert('提示', '所选行中存在过期问卷，无法发送问卷', 'warning');
                        _flag = false;
                        return false;
					}

                    // 0 未发送 1已发送
                    if('1'==_object.SENDSTATUS){
                        $.messager.alert('提示', '所选行中存在已发送数据，无法重复发送', 'warning');
                        _flag = false;
                        return false;
                    }
                });

                if(_flag){
                    var ss = [];
                    for (var i = 0; i < rows.length; i++) {
                        var row = rows[i];
                        ss.push({name: "ids", value: "" + (row.id || row.ID ) + ""});
                    }
                    $.messager.progress({text: ''});
                    $.ajax({
                        type: 'post',
                        url: '${pageContext.request.contextPath}/api/ebms/surveyInfo/send',
                        data: ss
                    }).done(function (data) {
                        if (data.code === 0) {
                            $.messager.alert('提示', '发送成功');
                            pg.search();
                        } else {
                            $.messager.alert('发送失败', data.errMsg, 'warning');
                        }
                    }).always(function () {
                        $.messager.progress('close');
                    });

                }
            },
            "onDelete":function(pg){
                var rows = pagegrid.getMultiSelected();

                if (!rows || rows.length === 0) {
                    $.messager.alert('警告', "请选择数据！", "warning");
                    return;
                }

                var _flag = true;

                $.each(rows,function(_index,_object){
                    // 0 未发送 1已发送
                    if('1'==_object.SENDSTATUS){
                        $.messager.alert('提示', '所选行中存在已发送数据，无法重复发送', 'warning');
                        _flag = false;
                        return false;
                    }
                });

                if(_flag){
                    pg.deleteData();
                }

            }
        };

		// grid加载成功后方法
        options.onPageLoadSuccess = function (res) {

            // body值
            $('body').data('pagegrid_data',res);

            var _rows = res.rows;

            // grid
           	var $datagrid_btable = $('.datagrid-view2 .datagrid-btable');

           	//================调查范围渲染 1 会员2 推荐人3 外勤人员================START
			var $cellScope = $datagrid_btable.find('.datagrid-cell-c1-SCOPENAME');
			$.each(_rows,function(_index,_object){
                var _scope = _object.SCOPE;
                var $cell = $($cellScope[_index]);

                var _arr = _scope.split(',');
                var _str_arr = new Array();
                _str_arr.push('<a href="javascript:void(0);" class="scopeFn" >');
                var _render_arr = new Array();
                for (var i =0;i < _arr.length;i++){
                    var _s = _arr[i];
                    _render_arr.push(',');
                    // 1会员 2推荐人 3外勤人员
                    if('1' == _s){
                        _render_arr.push('会员');
                    }

                    if('2' == _s){
                        _render_arr.push('推荐人');
                    }

                    if('3' == _s){
                        _render_arr.push('外勤人员');
                    }
                }
                var _temp_str = _render_arr.join('');
                var _render_str = _temp_str.substr(1);
                _str_arr.push(_render_str);
                _str_arr.push('</a>');
                var _render_real_str = _str_arr.join('');
                $cell.html(_render_real_str);
                $cell.find('.scopeFn').on('click',scopeFn);// 绑定点击方法

			});
            // 绑定数据index
            $cellScope.find('.scopeFn').each(function(_index,_object){
                $(_object).data('_index',_index);
            });
            //================调查范围渲染 1 会员2 推荐人3 外勤人员================END

           	//=======统计方法 渲染========START
           	var $lastCell = $datagrid_btable.find('.datagrid-cell-c1-STATISTICS');
            $lastCell.html('<a href="javascript:void(0);">统计</a>');
            $lastCell.find('a').on('click',statisticsFn); // 绑定点击方法
            // 绑定数据index
            $lastCell.find('a').each(function(_index,_object){
                $(_object).data('_index',_index);
			});
            //=======统计方法 渲染========END

        }
		//初始化
		pagegrid = new ehsure.PageGrid(options).build();


		
	})();
	
	//查看详细信息
    function viewDetail(id) {
    	pagegrid.openWin('detail', '', "id=" + id);
    }

    // 调查范围FN 1 会员2 推荐人3 外勤人员
    function scopeFn(){

        var _pagegrid_data = $('body').data('pagegrid_data');
        var _index = $(this).data('_index');
        var _rowNum = $(this).parents('.datagrid-view').find('.datagrid-cell-rownumber').eq(_index).html();
        var _row = _pagegrid_data.rows[_index];

        // $('#dd').data('scope_data',_row.SCOPE);

        var winTitle = '调查范围';
        var url = '${pageContext.request.contextPath}/view/ebms/surveyInfo/scopeDetail?sendTarget='+_row.SCOPE + '&id=' + _row.ID;
        // parent.addTab(winTitle, url);
        addDialog(winTitle,url);


    }


    // 统计FN
    function statisticsFn(){
        // debugger;
        var _pagegrid_data = $('body').data('pagegrid_data');
        var _index = $(this).data('_index');
        var _rowNum = $(this).parents('.datagrid-view').find('.datagrid-cell-rownumber').eq(_index).html();
        var _row = _pagegrid_data.rows[_index];

        var winTitle = '问卷统计';
        var url = '${pageContext.request.contextPath}/view/ebms/surveyInfo/statisticsDetail?id=' + _row.ID;
        // parent.addTab(winTitle, url);
        // addDialog(winTitle,url);
        openDialog(winTitle,url,1500,750);

	}

	function addDialog(title,url){
        // 开启对应的编辑页
        var content = '<iframe src="' + url + '" width="100%" height="99%" frameborder="0" scrolling="no"></iframe>';
        var boarddiv = '<div id="msgwindow" title="' + title + '"></div>'//style="overflow:hidden;"可以去掉滚动条
        $(document.body).append(boarddiv);
        var win = $('#msgwindow').window({
            top: 100,
            content: content,
            width: 1200,
            height: 700,
            modal: true,
            title: title,
            onClose: function () {

            }
        });
        win.dialog('open');
	}

    function openDialog(title,url,width,height){
        // 开启对应的编辑页
        var content = '<iframe src="' + url + '" width="100%" height="99%" frameborder="0" scrolling="yes"></iframe>';
        var boarddiv = '<div id="msgwindow" title="' + title + '"></div>'//style="overflow:hidden;"可以去掉滚动条
        $(document.body).append(boarddiv);
        var win = $('#msgwindow').window({
            top: 100,
            content: content,
            width: width,
            height: height,
            modal: true,
            title: title,
            onClose: function () {

            }
        });
        win.dialog('open');
    }


    function reloadDatagrid(){
        debugger;
        $(".datagrid-view").css("height","500")
        var pageNumber = $('.pagination-num').val();
        var pageSize = $('.pagination-page-list').val();
        pagegrid.search(pageNumber, pageSize);
    }

</script>
</body>
</html>